import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: 'http://localhost:1337', // url = base url + request url
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(config => {
  // console.log('请求拦截器', config)
  // 统一传入token
  if (store.getters.token) {
    if (config.url !== '/auth/local/register' && config.url !== '/auth/local') {
      config.headers.Authorization = 'Bearer ' + store.getters.token
    }
  }
  return config
},
error => {
  return Promise.reject(error)
}
)

// 响应拦截器
service.interceptors.response.use(response => {
  // console.log('响应拦截器', response)
  return response
},
error => {
  console.dir(error)
  // 对错误的统一处理
  if (error.response.status === 400) {
    Message.error(error.message)
  }
  return Promise.reject(error)
}
)

export default service
